import React from "react";
import { Redirect } from "react-router-dom";
import { Form, Input, Button, Checkbox, Typography } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { login } from "@/api/user";
import localUtils from "@/utils/local";
import "./login.less";
const { Title } = Typography;

export default function Login(props) {
  const onFinish = (value) => {
    const { username, password } = value;
    login({ us: username, ps: password }).then(res => {
      const user = {
        username: username,
        token: res.data.token
      };
      localUtils.user = user;
      localUtils.setUser(user);
      props.history.replace("/");
    });
  }
  const validatePwd = (rule, value, callback) => {
    if (!value) {
      return Promise.reject("请输入密码");
    } else if (value.length < 4) {
      return Promise.reject("密码长度不能小于4位");
    } else if (value.length > 12) {
      return Promise.reject("密码长度不能大于12位");
    } else {
      return Promise.resolve("验证通过");
    }
  }
  if (localUtils.user && localUtils.user.token) return <Redirect to='/' />;
  return (
    <div id='Login'>
      <Title className='Title'>React后台管理系统</Title>
      <Form
        name='normal_login'
        className='login-form'
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <Form.Item
          name='username'
          rules={[
            { required: true, whitespace: true, message: "请输入账号!" },
            { min: 4, message: "账号至少4位" },
            { max: 12, message: "账号最多12位" },
            {
              pattern: /^[a-zA-Z0-9_]+$/,
              message: "账号必须是英文、数字或下划线组成"
            }
          ]}
        >
          <Input
            prefix={<UserOutlined className='site-form-item-icon' />}
            placeholder='账号'
          />
        </Form.Item>
        <Form.Item name='password' rules={[{ validator: validatePwd }]}>
          <Input
            prefix={<LockOutlined className='site-form-item-icon' />}
            type='password'
            placeholder='密码'
          />
        </Form.Item>
        <Form.Item>
          <Form.Item name='remember' valuePropName='checked' noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>

          <a className='login-form-forgot' href='/#'>
            忘记密码
          </a>
        </Form.Item>

        <Form.Item>
          <Button
            type='primary'
            htmlType='submit'
            className='login-form-button'
          >
            登 录
          </Button>
          或 <a href='/#'>注册</a>
        </Form.Item>
      </Form>
    </div>
  );
}
